package hw1;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.googlecode.jatl.Html;
import com.mysql.jdbc.ResultSetMetaData;

public class Question {

    private int questionNumber;
    private String assumption;
    private String query;
    private String result; // in html format
    
    public Question(int questionNumber, String assumption, String query) {
        this.questionNumber = questionNumber;
        this.assumption = assumption;
        this.query = query;
    }
    
    @SuppressWarnings("unused")
    public void excecute(Statement st) throws SQLException {
        
        final ResultSet rs = st.executeQuery(query);
        final ResultSetMetaData rsmd = (com.mysql.jdbc.ResultSetMetaData)rs.getMetaData();
        
        final StringWriter writer = new StringWriter();
        Html html = new Html(writer) {{
            html();
                head();
                    link().rel("stylesheet").type("text/css").href("style.css").end();
                end(); //head
                body();
                    h3().text("Q" + getQuestionNumber()).end();
                    p().raw(assumption.replaceAll("\\n", "<br />")).end();
                    pre().raw(query.replaceAll("\\n", "</br>")).end();
                    br();
                    table().border("1");
                        thead().tr();
                        for (int i=1; i<=rsmd.getColumnCount(); i++) {
                            th().text(rsmd.getColumnName(i)).end();
                        } 
                        end().end(); // tr, thead
                        tbody();
                        while (rs.next()) {
                            tr();
                            for (int i=1; i<=rsmd.getColumnCount(); i++) {
                                Object o = rs.getObject(i);
                                td().text(o == null ? "null" : o.toString()).end();
                            }
                            end(); // tr
                        }
                        end(); // tbody
                    end(); // table
                end(); // body
            end(); // html
            done();
        }};

        result = writer.toString();

    }
    
    @Override
    public String toString() {
        return result;
    }

    public void setQuestionNumber(int questionNumber) {
        this.questionNumber = questionNumber;
    }

    public int getQuestionNumber() {
        return questionNumber;
    }
    
    public String getAssumption() {
        return assumption;
    }

    public void setAssumption(String assumption) {
        this.assumption = assumption;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }
    
}
